package com.liangxy.news.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.liangxy.news.R;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.repository.NewsRepository;
import com.liangxy.news.ui.main.home.HomeFragment;
import com.liangxy.news.ui.main.profile.ProfileFragment;
import com.liangxy.news.ui.main.settings.SettingsFragment;

/**
 * Main activity with bottom navigation
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private BottomNavigationView bottomNavigationView;
    private String categoryToOpen = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 检查是否有特定类别需要打开
        handleIntent(getIntent());
        
        // Initialize views
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        
        // Setup bottom navigation
        setupBottomNavigation();
        
        // Initialize database
        try {
            AppDatabase.getInstance(getApplicationContext());
            Log.d(TAG, "Database initialized successfully");
        } catch (Exception e) {
            Log.e(TAG, "Error initializing database: " + e.getMessage(), e);
        }
        
        // Load default fragment
        if (savedInstanceState == null) {
            // 如果有指定类别，则打开带有类别参数的HomeFragment
            if (categoryToOpen != null && !categoryToOpen.isEmpty()) {
                HomeFragment homeFragment = new HomeFragment();
                Bundle args = new Bundle();
                args.putString("CATEGORY", categoryToOpen);
                homeFragment.setArguments(args);
                loadFragment(homeFragment);
                Log.d(TAG, "打开指定类别新闻: " + categoryToOpen);
            } else {
                loadFragment(new HomeFragment());
            }
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }
    
    /**
     * 处理传入的Intent
     */
    private void handleIntent(Intent intent) {
        if (intent != null && intent.hasExtra("OPEN_CATEGORY")) {
            categoryToOpen = intent.getStringExtra("OPEN_CATEGORY");
            
            // 验证类别是否有效
            if (!isValidCategory(categoryToOpen)) {
                Log.w(TAG, "无效的新闻类别: " + categoryToOpen);
                categoryToOpen = NewsRepository.TYPE_TOP; // 默认使用推荐
            }
        }
    }
    
    /**
     * 检查类别是否有效
     */
    private boolean isValidCategory(String category) {
        if (category == null || category.isEmpty()) {
            return false;
        }
        
        return category.equals(NewsRepository.TYPE_TOP) ||
               category.equals(NewsRepository.TYPE_GUONEI) ||
               category.equals(NewsRepository.TYPE_GUOJI) ||
               category.equals(NewsRepository.TYPE_YULE) ||
               category.equals(NewsRepository.TYPE_TIYU) ||
               category.equals(NewsRepository.TYPE_JUNSHI) ||
               category.equals(NewsRepository.TYPE_KEJI) ||
               category.equals(NewsRepository.TYPE_CAIJING) ||
               category.equals(NewsRepository.TYPE_SHISHANG);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 应用退出时关闭数据库连接
        AppDatabase.closeDatabase();
        Log.d(TAG, "Closed database connection in onDestroy");
    }
    
    /**
     * Setup bottom navigation
     */
    private void setupBottomNavigation() {
        bottomNavigationView.setOnItemSelectedListener(item -> {
            Fragment fragment;
            
            int itemId = item.getItemId();
            if (itemId == R.id.navigation_home) {
                fragment = new HomeFragment();
                loadFragment(fragment);
                return true;
            } else if (itemId == R.id.navigation_profile) {
                fragment = new ProfileFragment();
                loadFragment(fragment);
                return true;
            } else if (itemId == R.id.navigation_settings) {
                fragment = SettingsFragment.newInstance();
                loadFragment(fragment);
                return true;
            }
            
            return false;
        });
    }
    
    @Override
    public void onBackPressed() {
        // 检查Fragment栈中是否有Fragment
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }
    
    /**
     * Load fragment
     * @param fragment Fragment to load
     */
    private void loadFragment(Fragment fragment) {
        try {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragmentContainer, fragment);
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            Log.e(TAG, "加载Fragment失败: " + e.getMessage(), e);
        }
    }
} 